<?php
declare(strict_types=1);

namespace src\database;

use src\Application;
use src\database\connectors\DbFactory;

class DatabaseManager
{
    /**
     * @var Application
     */
    protected $app;

    protected $connections = [];

    /**
     * @param Application $app
     */
    public function __construct( $app)
    {
        $this->app = $app;
    }

    public function connection($name = 'mysql')
    {
        if (!isset($this->connections[$name])){
            $this->connections[$name] = $this->makeConnection($name);
        }
        return $this->connections[$name];
    }

    protected function makeConnection($name)
    {
        $config = $this->configuration($name);
        return (new DbFactory)->make($config, $name);
    }

    protected function configuration($name )
    {
        $name = $name ?: $this->getDefaultConnection();
        $connections = $this->app['config']['database.connections'];
        if (!isset($connections[$name])){
            throw new \Exception("{$name} 数据库配置不存在");
        }
        return $connections[$name];
    }


    protected function getDefaultConnection()
    {
        return $this->app['config']['database.default'];
    }

    public function __call($method, $arguments)
    {
        return $this->connection()->$method(...$arguments);
    }
}